
import urllib2
import base64
from xml.dom.minidom import parse, parseString
#import easy to use xml parser called minidom:


xmlfile = ".//schema/xentxtdata.xml"
certfile = "x509.cert"
keyfile  = "out.pub"
tempxml  = "temp.xml"
tempcert = "temp.cert"
tempkey =  "temp.key"

#all these imports are standard on most modern python implementations
def gen_out_xml():
    dom = parse(xmlfile)
    root = dom.getElementsByTagName("xentxt:xentxtdata")
    xencert = dom.getElementsByTagName('xentxt:xencert')[0]
    xenpub  = dom.getElementsByTagName("xentxt:xenpubkey")[0]
    print xencert.firstChild.nodeValue
    print xenpub.firstChild.nodeValue
    f= open (certfile)
    cert = base64.b64encode(f.read())
    print cert
    xencert.firstChild.nodeValue = cert
    f.close()
    f = open(keyfile)
    key = base64.b64encode(f.read())
    xenpub.firstChild.nodeValue = key
    f.close()
    f = open(tempxml,"w");
    print dom.toxml()
    f.write(dom.toxml())
    f.close()
def read_in_xml():
    dom = parse(tempxml)
    root = dom.getElementsByTagName("xentxt:xentxtdata")
    xencert = dom.getElementsByTagName('xentxt:xencert')[0]
    xenpub  = dom.getElementsByTagName("xentxt:xenpubkey")[0]
    print xencert.firstChild.nodeValue
    print xenpub.firstChild.nodeValue
    f= open (tempcert,"w")
    cert = base64.b64decode(xencert.firstChild.nodeValue)
    f.write(cert)
    f.close()
    f = open(tempkey,"w")
    key = base64.b64decode( xenpub.firstChild.nodeValue)
    f.write(key)
    f.close()
    #print dom.toxml()
#print xenpub..firstChild.nodeValue


if __name__ == '__main__':
    gen_out_xml()
    read_in_xml()
